package com.example.rabbitmq.controller;

import com.example.rabbitmq.config.RabbitmqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/11/14
 */

@Slf4j
@RestController
public class ProducerController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 队列设置TTL
     * @param msg
     * @return
     */
    @GetMapping("/send/{msg}")
    public String msg(@PathVariable("msg") String msg) {
        log.info("当前时间：{},发送一条信息给两个 TTL 队列:{}", LocalDateTime.now(), msg);
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_X, RabbitmqConfig.ROUTING_KEY_XA, "消息来自 ttl 为 10S 的队列: " + msg);
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_X, RabbitmqConfig.ROUTING_KEY_XB, "消息来自 ttl 为 40s 的队列: " + msg);
        return "发送消息成功";
    }

    /**
     * 消息设置TTL
     * @param msg
     * @param ttl
     * @return
     */
    @GetMapping("/send/{msg}/{ttl}")
    public String msg(@PathVariable("msg") String msg, @PathVariable("ttl") Integer ttl) {
        log.info("当前时间：{},发送一条时长{}毫秒 TTL 信息给队列:{}", LocalDateTime.now(), ttl, msg);
        MessagePostProcessor messagePostProcessor = (message) -> {
            message.getMessageProperties().setExpiration(String.valueOf(ttl));
            return message;
        };
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_X, RabbitmqConfig.ROUTING_KEY_XC, msg, messagePostProcessor);
        return "发送消息成功";
    }

    /**
     * 延时队列
     * @param msg
     * @param ttl
     * @return
     */
    @GetMapping("/sendByDelay/{msg}/{ttl}")
    public String msgbyDelay(@PathVariable("msg") String msg, @PathVariable("ttl") Integer ttl) {
        log.info("当前时间：{},发送一条时长{}毫秒 TTL 信息给队列:{}", LocalDateTime.now(), ttl, msg);
        MessagePostProcessor messagePostProcessor = (message) -> {
            // 注意，这里不再是 setExpiration ，而是 setDelay
            message.getMessageProperties().setDelay(ttl);
            return message;
        };
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE, RabbitmqConfig.ROUTING_KEY, msg, messagePostProcessor);
        return "发送消息成功";
    }

}
